#  -*- coding: utf-8 -*-

from .base_stop_loss import BaseStopLoss
from data.data_module import DataModule
from factor.factor_module import FactorModule



class FixMA20StopLoss(BaseStopLoss):
    def __init__(self, account, max_loss):
        BaseStopLoss.__init__(self, account)
        self.max_loss = max_loss

    def update_holding(self, code, date):
        pass

    def is_stop(self, code, date):
        """
        判断股票在当前日期是否需要止损
        :param code: 股票代码
        :param date: 日期
        :return: True - 止损， False - 不止损
        """
        print('止损判断：%s' % code, flush=True)
        dm = DataModule()
        fm = FactorModule()
        dm_daily = dm.get_k_data(code, index = False, autype="hfq", begin_date=date, end_date=date)
        fm_daily = fm.get_single_stock_factors(code, "hfq_ma",False, begin_date=date, end_date=date)
        if dm_daily.index.size > 0 and fm_daily.index.size > 0:
            dm_daily.set_index(['date'], 1, inplace=True)
            fm_daily.set_index(['date'], 1, inplace=True)
            dm_trading_daily = dm_daily.loc[dm_daily.is_trading == True, :]
            if dm_trading_daily.index.size > 0:
                change_rate = round(100 * (dm_trading_daily.loc[date]["close"] - fm_daily.loc[date]["ma20"])/fm_daily.loc[date]["ma20"],2)
                if change_rate < 3:
                    return True

        return False

